# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/4/24
import os
import random
import shutil
from time import sleep

from lib.tools import keep_tmp_images_clean
from submodules.common.lib.datetime_ import get_timestamp, get_timestamp_unix
from submodules.common.lib import json_, os_

from compat import project_paths
from lib.adb_ import (
    get_screenshot,
    swipe_by_bounds,
    click_by_bounds,
    click_by_image,
    is_exsit,
    init_screenshot_path,
)

from lib.baidu_ocr import get_verify_code_by_baidu_ocr
from lib.haoi import get_verify_code_by_haoi
from lib.tujian import get_verify_code_by_tujian_ocr

from obj import obj_info
from lib.image_ import img_cut

from submodules.common.lib.log_ import get_logger

from compat.project_paths import project_path
from submodules.common.lib.send_email import send_email_remind

obj_path = os.path.join(project_path, "obj")

logger = get_logger(__file__)

# mode = "一阶降妖"
mode = "一阶附魔"

# global screenshot_path
# screenshot_path = None

has_random_events = False


def process_get_verify_code_by_haoi():
    os.environ["screenshot_path"] = get_screenshot()

    验证码图片路径 = img_cut(
        os.environ["screenshot_path"], obj_info.主页面__老君查岗弹窗_验证码类型_已擦除__弹窗完整区域["bounds"]
    )
    # 测试
    # screenshot_path = "D:\code\wendao\obj\主页面\老君查岗弹窗_验证码类型_已擦除.png"
    # 验证码图片路径 = img_cut(screenshot_path, obj_info.主页面__老君查岗弹窗_验证码类型_已擦除__弹窗完整区域["bounds"])

    logger.info("获取验证码值")
    验证码值 = get_verify_code_by_haoi(验证码图片路径)
    return 验证码值, 验证码图片路径


def 开启如意刷道令(times=1, timeout=60):
    timestamp_start = get_timestamp_unix()
    while True:
        time_spent = int(get_timestamp_unix()) - int(timestamp_start)
        if time_spent > timeout:
            break

        is_lao_jun = is_exsit(obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__弹窗标题)
        if is_lao_jun:
            break

        click_by_image(obj_info.战斗中页面__默认__展开按钮)
        click_by_image(obj_info.战斗中页面__菜单弹窗__刷道按钮)
        click_by_image(obj_info.主页面__默认__刷道按钮)

        res = is_exsit(obj_info.主页面__刷道弹窗__标题)
        if res:
            click_by_image(obj_info.主页面__刷道弹窗_如意刷道令关闭__如意刷道令开关)
            sleep(1)
            res2 = is_exsit(obj_info.主页面__刷道弹窗_如意刷道令开启__如意刷道令开关)
            sleep(1)
            res3 = click_by_image(obj_info.主页面__刷道弹窗_如意刷道令为0__数值区域)

            click_by_image(obj_info.主页面__刷道弹窗_如意刷道令关闭__如意刷道令开关)
            sleep(1)
            res22 = is_exsit(obj_info.主页面__刷道弹窗_如意刷道令开启__如意刷道令开关)
            sleep(1)
            res33 = click_by_image(obj_info.主页面__刷道弹窗_如意刷道令为0__数值区域)

            click_by_image(obj_info.主页面__刷道弹窗_如意刷道令关闭__如意刷道令开关)
            sleep(1)
            res222 = is_exsit(obj_info.主页面__刷道弹窗_如意刷道令开启__如意刷道令开关)
            sleep(1)
            res333 = click_by_image(obj_info.主页面__刷道弹窗_如意刷道令为0__数值区域)

            if res2 and not res3:
                click_by_image(obj_info.主页面__如意刷道令购买弹窗__关闭按钮)
                click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                return True
            if res22 and not res33:
                click_by_image(obj_info.主页面__如意刷道令购买弹窗__关闭按钮)
                click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                return True
            if res222 and not res333:
                click_by_image(obj_info.主页面__如意刷道令购买弹窗__关闭按钮)
                click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                return True

            if is_exsit(obj_info.主页面__刷道弹窗_如意刷道令为0__数值区域):
                click_by_image(obj_info.主页面__刷道弹窗_如意刷道令开启__购买按钮)
                if times == 2:
                    click_by_image(obj_info.主页面__如意刷道令购买弹窗__增加数量按钮)  # 增加购买次数
                click_by_image(obj_info.主页面__如意刷道令购买弹窗__购买按钮)

            click_by_image(obj_info.主页面__如意刷道令购买弹窗__关闭按钮)
            click_by_image(obj_info.主页面__刷道弹窗_如意刷道令关闭__如意刷道令开关)
            # click_by_image(obj_info.主页面__刷道弹窗__关闭按钮)


def 刷道():
    # 识别结果保存路径
    verify_code_data_dir = os.path.join(
        project_paths.project_tmp_path, "verify_code_data"
    )
    os_.mkdir_soft(verify_code_data_dir)

    是否固定队 = True
    count = 0
    是否已开启如意刷道令 = False
    while True:
        count += 1
        # 定时关闭
        min_str = get_timestamp()[8:12]
        if 2000 > int(min_str) > 1831:
            logger.info("全局时间，停止操作，仅保持APP运行。")
            sleep(10)
        elif 2000 < int(min_str):
            logger.info("执行押镖任务")
            exit(0)
        else:
            是否已开启如意刷道令 = True
            # 定时开启如意刷道令
            if not 是否已开启如意刷道令:
                min_str = get_timestamp()[8:12]
                if 1500 > int(min_str) > 1300:
                    logger.info("开启如意刷道令。")
                    res = 开启如意刷道令(2)
                    if res:
                        是否已开启如意刷道令 = True

            if 是否固定队:
                pass
            else:
                if is_exsit(obj_info.主页面__默认__刷道按钮):
                    click_by_image(obj_info.主页面__默认_选中任务按钮__队伍按钮)
                    click_by_image(obj_info.主页面__默认_选中组队按钮__队伍按钮)
                if is_exsit(obj_info.主页面__队伍弹窗_一阶伏魔__一阶伏魔文案):
                    logger.info("已选择好活动类型")
                else:
                    click_by_image(
                        obj_info.主页面__队伍弹窗_一阶伏魔__一阶伏魔文案, obj_info.主页面__队伍弹窗_默认__关闭按钮
                    )
                    click_by_image(obj_info.主页面__队伍弹窗_队伍信息弹窗__刷道选项)
                    click_by_image(obj_info.主页面__队伍弹窗_队伍信息弹窗__一阶伏魔选项)
                    click_by_image(obj_info.主页面__队伍弹窗_队伍信息弹窗__开始匹配按钮)
                is_need_match = is_exsit(obj_info.主页面__队伍弹窗_默认__5号队员守护标识)
                if is_need_match:
                    click_by_image(obj_info.主页面__队伍弹窗_默认__开始匹配按钮)
                click_by_image(obj_info.主页面__队伍弹窗_默认__关闭按钮)

            init_screenshot_path()
            click_by_image(obj_info.主页面__默认__刷道按钮)
            if mode == "一阶降妖":
                pass

            if mode == "一阶附魔":
                init_screenshot_path()
                click_by_image(obj_info.主页面__默认__刷道按钮)
                init_screenshot_path()
                click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                res = click_by_image(obj_info.主页面__伏魔对话框__一阶伏魔按钮)
                if res:
                    # 等待弹出老君对话框
                    for i in range(5):
                        init_screenshot_path()
                        is_lao_jun = is_exsit(obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__弹窗标题)
                        if is_lao_jun:
                            break
                        # 如果没有老君弹窗则继续操作
                        click_by_image(obj_info.主页面__默认__刷道按钮)
                        res = click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                        if res:
                            break
                    if is_lao_jun:
                        pass
                    else:
                        init_screenshot_path()
                        click_by_image(obj_info.主页面__默认__刷道按钮)
                        click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)
                        click_by_image(obj_info.主页面__伏魔对话框2__除魔卫道按钮)
                        # click_by_image(obj_info.主页面__刷道弹窗__关闭按钮)

                    if count < 100:
                        click_by_image(obj_info.主页面__双倍确认弹窗__取消按钮)
                        click_by_image(obj_info.主页面__如意刷道令提示弹窗__取消按钮)
            is_lao_jun = is_exsit(obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__弹窗标题)
            logger.info(f"is_lao_jun:{is_lao_jun}")
            if is_lao_jun:
                logger.info("处理太上老君")
                # 擦除
                logger.info("擦除")
                bounds = obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码区域["bounds"]
                swipe_by_bounds(*bounds)

                # 等待擦除完成
                for i in range(20):
                    res = is_exsit(obj_info.主页面__老君查岗弹窗_验证码类型_已擦除__验证码区域检查点)
                    if res:
                        break
                    init_screenshot_path()
                    sleep(1)

                # 增大重试次数为20次
                is_use_haoi = False
                for i in range(20):
                    res = process_get_verify_code_by_haoi()
                    验证码值 = res[0]
                    验证码图片路径 = res[1]
                    logger.info(f"使用好爱打码识别")
                    logger.info(f"好爱第{i + 1}次获取：")
                    logger.info(f"验证码值:{验证码值}")

                    if 验证码值 in ["1", "2", "3", "4"]:
                        is_use_haoi = True
                        break

                if is_use_haoi:
                    if 验证码值 == "1":
                        click_by_bounds(
                            *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项1["bounds"]
                        )
                    if 验证码值 == "2":
                        click_by_bounds(
                            *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项2["bounds"]
                        )
                    if 验证码值 == "3":
                        click_by_bounds(
                            *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项3["bounds"]
                        )
                    if 验证码值 == "4":
                        click_by_bounds(
                            *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项4["bounds"]
                        )
                    try:
                        验证码图片保存路径 = f"{get_timestamp()}_{验证码值}.png"
                        shutil.copy(
                            验证码图片路径, os.path.join(verify_code_data_dir, 验证码图片保存路径)
                        )
                        logger.info(验证码图片保存路径)
                    except Exception as e:
                        logger.error(repr(e))
                    screenshot_path = os.environ["screenshot_path"]
                else:
                    # 好爱识别失败
                    # 1、使用OCR识别后点击一个
                    # 2、发送邮件提醒
                    # 3、退出程序

                    # 发送邮件提醒
                    send_email_remind()

                    验证码值 = ""
                    os.environ["screenshot_path"] = get_screenshot()
                    验证码图片路径 = img_cut(
                        os.environ["screenshot_path"],
                        obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码区域["bounds"],
                    )

                    is_int = False
                    if 验证码值.__len__() <= 1 or not is_int:
                        # 不合理验证码则切换获取方式再获取一次
                        验证码值 = get_verify_code_by_baidu_ocr(验证码图片路径)
                        logger.info(f"使用百度OCR识别")
                        logger.info(f"验证码值:{验证码值}")

                    try:
                        int(验证码值)
                        is_int = True
                    except:
                        is_int = False
                    if 验证码值.__len__() <= 1 or not is_int:
                        # 不合理验证码则切换获取方式再获取一次
                        验证码值 = get_verify_code_by_tujian_ocr(验证码图片路径)
                        logger.info(f"使用图鉴OCR识别")
                        logger.info(f"验证码值:{验证码值}")

                    选项图片路径1 = img_cut(
                        screenshot_path,
                        obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项1["bounds"],
                    )
                    选项值1 = get_verify_code_by_baidu_ocr(选项图片路径1)
                    选项图片路径2 = img_cut(
                        screenshot_path,
                        obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项2["bounds"],
                    )
                    选项值2 = get_verify_code_by_baidu_ocr(选项图片路径2)
                    选项图片路径3 = img_cut(
                        screenshot_path,
                        obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项3["bounds"],
                    )
                    选项值3 = get_verify_code_by_baidu_ocr(选项图片路径3)
                    选项图片路径4 = img_cut(
                        screenshot_path,
                        obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项4["bounds"],
                    )
                    选项值4 = get_verify_code_by_baidu_ocr(选项图片路径4)
                    is_choosed = False
                    if is_choosed == False:
                        if 验证码值 == 选项值1:
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项1["bounds"]
                            )
                            logger.info(f"点击了第1个选项")
                    if is_choosed == False:
                        if 验证码值 == 选项值2:
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项2["bounds"]
                            )
                            logger.info(f"点击了第2个选项")
                    if is_choosed == False:
                        if 验证码值 == 选项值3:
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项3["bounds"]
                            )
                            logger.info(f"点击了第3个选项")
                    if is_choosed == False:
                        if 验证码值 == 选项值4:
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项4["bounds"]
                            )
                            logger.info(f"点击了第4个选项")
                    if is_choosed == False:
                        # 获取所有选项值
                        logger.info("完全匹配没有成功，使用模糊匹配")

                        # 获得选项得分
                        score_data = {}

                        score_tmp = 0
                        cursor = 0
                        s1 = 验证码值
                        s2 = 选项值1
                        for i1 in range(s1.__len__()):
                            for i2 in range(cursor, s2.__len__()):
                                if s1[i1] == s2[i2]:
                                    score_tmp += 1
                                    cursor = i2
                                    score_data.update({"1": score_tmp})
                        score_tmp = 0
                        cursor = 0
                        s1 = 验证码值
                        s2 = 选项值2
                        for i1 in range(s1.__len__()):
                            for i2 in range(cursor, s2.__len__()):
                                if s1[i1] == s2[i2]:
                                    score_tmp += 1
                                    cursor = i2
                                    score_data.update({"2": score_tmp})
                        score_tmp = 0
                        cursor = 0
                        s1 = 验证码值
                        s2 = 选项值3
                        for i1 in range(s1.__len__()):
                            for i2 in range(cursor, s2.__len__()):
                                if s1[i1] == s2[i2]:
                                    score_tmp += 1
                                    cursor = i2
                                    score_data.update({"3": score_tmp})
                        score_tmp = 0
                        cursor = 0
                        s1 = 验证码值
                        s2 = 选项值4
                        for i1 in range(s1.__len__()):
                            for i2 in range(cursor, s2.__len__()):
                                if s1[i1] == s2[i2]:
                                    score_tmp += 1
                                    cursor = i2
                                    score_data.update({"4": score_tmp})

                        score_data_sorted = sorted(
                            score_data.items(), key=lambda x: x[1], reverse=True
                        )
                        logger.info(f"score_data_sorted:{score_data_sorted}")
                        best_option = score_data_sorted[0]

                        # 根据得分匹配选项
                        try:
                            best_option_number = best_option[0]
                            best_option_score = best_option[1]
                        except:
                            best_option_number = 0
                            best_option_score = 0

                        is_choosed = False
                        if is_choosed == False and best_option_number == "1":
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项1["bounds"]
                            )
                            logger.info(f"点击了第1个选项")
                        if is_choosed == False and best_option_number == "2":
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项2["bounds"]
                            )
                            logger.info(f"点击了第2个选项")
                        if is_choosed == False and best_option_number == "3":
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项3["bounds"]
                            )
                            logger.info(f"点击了第3个选项")
                        if is_choosed == False and best_option_number == "4":
                            is_choosed = True
                            click_by_bounds(
                                *obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项4["bounds"]
                            )
                            logger.info(f"点击了第4个选项")
                        if is_choosed == False:
                            rand_num = random.randint(1, 4)
                            eval(
                                f'click_by_bounds(*obj_info.主页面__老君查岗弹窗_验证码类型_未擦除__验证码选项{rand_num}["bounds"])'
                            )
                            logger.info("好爱识别异常，使用OCR识别，所有选项得分均为0，随机点击一个，待排查问题！")

                    # 退出程序
                    exit(0)

            if mode == "一阶降妖" and is_lao_jun:
                pass

            if mode == "一阶附魔" and is_lao_jun:
                init_screenshot_path()
                click_by_image(obj_info.主页面__默认__刷道按钮)
                init_screenshot_path()
                click_by_image(obj_info.主页面__刷道弹窗__伏魔前往按钮)

            click_by_image(obj_info.主页面__宠物信息弹窗__关闭按钮)
            click_by_image(obj_info.主页面__活动弹窗_默认__关闭按钮)

            # click_by_image(obj_info.主页面__对话框_默认__关闭按钮)
            click_by_image(obj_info.主页面__伏魔对话框2__除魔卫道按钮)
            click_by_image(obj_info.主页面__伏魔对话框3__我这就去按钮)

            # 清理图片
            # keep_tmp_images_clean(1000)


def 除暴():
    while True:
        click_by_image(obj_info.主页面__默认__活动按钮)
        sleep(1)
        res = is_exsit(obj_info.主页面__活动弹窗_默认__弹窗标题)
        if res:
            res1 = is_exsit(obj_info.主页面__活动弹窗_除暴未完成__任务文案1)
            if not res1:
                click_by_image(obj_info.主页面__活动弹窗_默认__关闭按钮)
                break

        click_by_image(obj_info.主页面__活动弹窗_默认__前往按钮1, obj_info.主页面__活动弹窗_除暴未完成__任务文案1)
        click_by_image(obj_info.主页面__除暴对话框__除暴安良按钮)

        click_by_image(obj_info.主页面__活动弹窗_默认__关闭按钮)
        click_by_image(obj_info.主页面__宠物信息弹窗__关闭按钮)
        click_by_image(obj_info.主页面__对话框_默认__关闭按钮)


def 修行():
    while True:
        click_by_image(obj_info.主页面__默认__活动按钮)
        sleep(1)
        res = is_exsit(obj_info.主页面__活动弹窗_默认__弹窗标题)
        if res:
            res2 = is_exsit(obj_info.主页面__活动弹窗_修行未完成__任务图标2)
            res3 = is_exsit(obj_info.主页面__活动弹窗_修行未完成2__任务图标3)
            res4 = is_exsit(obj_info.主页面__活动弹窗_修行未完成3__任务图标1)

            if not res2 and not res3 and not res4:
                click_by_image(obj_info.主页面__活动弹窗_默认__关闭按钮)
                break

        res = is_exsit(obj_info.主页面__活动弹窗_默认__弹窗标题)
        if res:
            has_click = False
            if not has_click:
                click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮3, obj_info.主页面__活动弹窗_修行未完成2__任务图标3
                )
                if is_over_100:
                    click_by_image(obj_info.主页面__十绝阵对话框__我去挑战按钮)
                else:
                    click_by_image(obj_info.主页面__修行对话框__我这就去按钮)
                res = click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮3, obj_info.主页面__活动弹窗_修行未完成2__任务图标3
                )
                if res:
                    has_click = True
            if not has_click:
                click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮2, obj_info.主页面__活动弹窗_修行未完成__任务图标2
                )
                if is_over_100:
                    click_by_image(obj_info.主页面__十绝阵对话框__我去挑战按钮)
                else:
                    click_by_image(obj_info.主页面__修行对话框__我这就去按钮)
                res = click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮2, obj_info.主页面__活动弹窗_修行未完成__任务图标2
                )
                if res:
                    has_click = True
            if not has_click:
                click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮1, obj_info.主页面__活动弹窗_修行未完成3__任务图标1
                )
                if is_over_100:
                    click_by_image(obj_info.主页面__十绝阵对话框__我去挑战按钮)
                else:
                    click_by_image(obj_info.主页面__修行对话框__我这就去按钮)
                res = click_by_image(
                    obj_info.主页面__活动弹窗_默认__前往按钮1, obj_info.主页面__活动弹窗_修行未完成3__任务图标1
                )
                if res:
                    has_click = True
        click_by_image(obj_info.主页面__活动弹窗_默认__关闭按钮)
        click_by_image(obj_info.主页面__宠物信息弹窗__关闭按钮)
        click_by_image(obj_info.主页面__对话框_默认__关闭按钮)


def main():
    while True:
        date_today_str = get_timestamp()[:8]

        # 日常任务
        logger.info("执行任务")

        task_list = [
            "除暴",
            "修行",
            "刷道",
        ]

        # 获取配置文件信息
        config_file_name = "team_task.json"
        config_file_path = os.path.join(
            project_paths.project_tmp_path, config_file_name
        )
        try:
            config_json = json_.json_file_to_dict(config_file_path)
        except:
            date_today_str = get_timestamp()[:8]
            config_json = {date_today_str: []}
            json_.dict_to_json_file(config_json, config_file_path)

        try:
            账号任务情况 = config_json[date_today_str]
        except:
            config_json = {date_today_str: []}
            账号任务情况 = config_json[date_today_str]

        for task in task_list:
            if task not in 账号任务情况:
                logger.info(f"当前执行任务{task}")
                eval(f"{task}()")
                账号任务情况.append(task)

            json_.dict_to_json_file(config_json, config_file_path)


if __name__ == "__main__":
    global is_over_100
    is_over_100 = True

    main()
    # 开启如意刷道令()

    # res = process_get_verify_code_by_haoi()
    # print(res)
    # '''
    # ('2', 'D:\\code\\wendao_tmp\\tmp_images\\20220625103558--8be2bad7-f42f-11ec-9389-78acc0c18657.png')
    # '''
